<template>
  <div 
    class="h-screen bg-gray-50 flex flex-col select-none"
    @contextmenu.prevent="handleGlobalContextMenu"
    @selectstart="handleGlobalSelection"
    @mousedown="handleGlobalSelection"
  >
    <!-- Windows风格应用程序菜单栏 -->
    <div class="bg-gray-800 text-white flex-shrink-0 fixed top-0 left-0 right-0 z-10">
      <div class="flex items-center h-10 px-4">
        <!-- 文件菜单 -->
        <div class="relative group">
          <button class="px-3 py-2 hover:bg-gray-700 text-sm">
            文件
          </button>
          <div class="absolute top-full left-0 bg-white border border-gray-200 shadow-lg rounded-md py-1 min-w-32 hidden group-hover:block z-50">
            <button @click="currentView = 'home'" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              首页
            </button>
            <button @click="currentView = 'settings'" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              扫描配置
            </button>
            <div class="border-t border-gray-200 my-1"></div>
            <button @click="exitApp" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              退出
            </button>
          </div>
        </div>

        <!-- 编辑菜单 -->
        <div class="relative group">
          <button class="px-3 py-2 hover:bg-gray-700 text-sm">
            编辑
          </button>
          <div class="absolute top-full left-0 bg-white border border-gray-200 shadow-lg rounded-md py-1 min-w-32 hidden group-hover:block z-50">
            <button @click="currentView = 'cache'" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              项目记录
            </button>
            <button @click="clearCache" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              清除缓存
            </button>
          </div>
        </div>

        <!-- 工具菜单 -->
        <div class="relative group">
          <button class="px-3 py-2 hover:bg-gray-700 text-sm">
            工具
          </button>
          <div class="absolute top-full left-0 bg-white border border-gray-200 shadow-lg rounded-md py-1 min-w-32 hidden group-hover:block z-50">
            <button @click="currentView = 'scanning'" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              扫描进度
            </button>
            <button @click="currentView = 'results'" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              扫描结果
            </button>
            <button @click="currentView = 'fileTypes'" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              文件类型设置
            </button>
          </div>
        </div>

        <!-- 帮助菜单 -->
        <div class="relative group">
          <button class="px-3 py-2 hover:bg-gray-700 text-sm">
            帮助
          </button>
          <div class="absolute top-full left-0 bg-white border border-gray-200 shadow-lg rounded-md py-1 min-w-32 hidden group-hover:block z-50">
            <button @click="currentView = 'help'" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              帮助文档
            </button>
            <div class="border-t border-gray-200 my-1"></div>
            <button @click="showAbout" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              关于
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区域 - 明确高度限制，无滚动条 -->
    <main class="flex-1 overflow-hidden pt-10">
      <!-- 首页 -->
      <HomePage 
        v-if="currentView === 'home'"
        @navigate="currentView = $event as 'home' | 'settings' | 'scanning' | 'results' | 'cache' | 'help' | 'fileTypes'"
        @test-api="testTauriAPI"
      />

      <!-- 设置页面 -->
      <ScanConfig 
        v-else-if="currentView === 'settings'"
        v-model:scan-mode="scanMode"
        v-model:detection-mode="detectionMode"
        v-model:similarity-threshold="similarityThreshold"
        v-model:scan-path="scanPath"
        v-model:min-file-size="minFileSize"
        v-model:max-file-size="maxFileSize"
        :has-project-record="!!currentProjectRecord"
        :project-record-info="currentProjectRecord"
        @navigate="currentView = $event as 'home' | 'settings' | 'scanning' | 'results' | 'cache' | 'help' | 'fileTypes'"
        @select-directory="selectDirectory"
        @start-scan="startScan($event)"
        ref="scanConfigRef"
      />

      <!-- 扫描进度页面 -->
      <ScanProgress 
        v-else-if="currentView === 'scanning'"
        :scan-progress="{
          scannedFiles: scannedFiles,
          duplicateGroups: duplicateGroups,
          savedSpace: savedSpace,
          stage: currentStage,
          status: currentStatus,
          subStatus: currentSubStatus,
          message: currentStatus,
          percentage: scanProgress
        }"
        :is-scanning="true"
        @cancel-scan="cancelScan"
      />

      <!-- 扫描结果页面 -->
      <ScanResults 
        v-else-if="currentView === 'results'"
        :total-files="totalFiles"
        :duplicate-groups="duplicateGroups"
        :duplicate-files="duplicateFiles"
        :saved-space="savedSpace"
        :duplicate-groups-list="duplicateGroupsList"
        @navigate="currentView = $event as 'home' | 'settings' | 'scanning' | 'results' | 'cache' | 'help' | 'fileTypes'"
        @update-groups="updateDuplicateGroups"
      />

      <!-- 缓存管理页面 -->
      <CacheManager 
        v-else-if="currentView === 'cache'"
        @navigate="currentView = $event as 'home' | 'settings' | 'scanning' | 'results' | 'cache' | 'help' | 'fileTypes'"
        @load-cache="loadFromCache"
        @go-to-scan="goToScanFromCache"
      />

      <!-- 文件类型设置页面 -->
      <FileTypeSettings 
        v-else-if="currentView === 'fileTypes'"
        @navigate="currentView = $event as 'home' | 'settings' | 'scanning' | 'results' | 'cache' | 'help' | 'fileTypes'"
      />

      <!-- 帮助页面 -->
      <HelpPage 
        v-else-if="currentView === 'help'"
        @navigate="currentView = $event as 'home' | 'settings' | 'scanning' | 'results' | 'cache' | 'help' | 'fileTypes'"
      />
    </main>

    <!-- 关于对话框 -->
    <div v-if="showAboutDialog" class="modal-overlay" ref="modalRef">
      <div class="modal-content max-w-md w-full mx-4">
        <div class="p-6">
          <div class="text-center">
            <div class="mx-auto w-16 h-16 bg-gradient-to-r from-blue-600 to-purple-600 rounded-full flex items-center justify-center mb-4">
              <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
            </div>
            <h3 class="text-lg font-semibold text-gray-900 mb-2">文件去重器</h3>
            <p class="text-sm text-gray-600 mb-4">版本 1.0.0</p>
            <p class="text-sm text-gray-600 mb-4">
              智能文件去重工具，帮助您快速识别和清理重复文件，释放存储空间。
            </p>
            <div class="border-t border-gray-200 pt-4 mb-6">
              <p class="text-sm text-gray-600 mb-2">开发商：</p>
              <p class="text-sm font-medium text-blue-600 mb-1">河南宾纳瑞网络科技有限公司</p>
              <a href="https://www.binnarui.com" target="_blank" class="text-sm text-blue-500 hover:text-blue-700 underline">
                https://www.binnarui.com
              </a>
            </div>
            <button 
              @click="showAboutDialog = false"
              class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition-colors"
            >
              确定
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style>
/* 全局禁止选择文本 */
* {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* 允许选择文本的元素 */
[data-allow-selection="true"],
input, textarea, select,
[contenteditable="true"],
pre, code {
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
}

/* 右键菜单元素允许选择 */
[data-context-menu-id] {
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
}

/* 确保按钮和链接等交互元素不可选择 */
button, a, [role="button"] {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
</style>

<style>
/* 统一弹窗定位系统 - 使用absolute定位避免fixed问题 */
:root {
  --modal-z-index: 9999;
  --modal-backdrop-color: rgba(0, 0, 0, 0.5);
}

/* 确保根容器有正确的定位上下文 */
#app {
  position: relative !important;
}

/* 弹窗容器 - 使用absolute定位 */
.modal-overlay {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  width: 100% !important;
  height: 100% !important;
  z-index: var(--modal-z-index) !important;
  background-color: var(--modal-backdrop-color) !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

/* 弹窗内容 - 使用absolute定位配合transform */
.modal-content {
  position: absolute !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  max-width: 90vw !important;
  max-height: 90vh !important;
  overflow: auto !important;
  background: white !important;
  border-radius: 8px !important;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04) !important;
}

/* 确保所有弹窗都使用统一类名 */
[class*="fixed"][class*="inset-0"] {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  z-index: var(--modal-z-index) !important;
}

[class*="absolute"][class*="top-1/2"][class*="left-1/2"] {
  position: absolute !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
}
</style>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, provide } from 'vue'
import { invoke } from '@tauri-apps/api/tauri'
import { listen } from '@tauri-apps/api/event'
import HomePage from './components/HomePage.vue'
import ScanConfig from './components/ScanConfig.vue'
import ScanProgress from './components/ScanProgress.vue'
import ScanResults from './components/ScanResults.vue'
import CacheManager from './components/CacheManager.vue'
import HelpPage from './components/HelpPage.vue'
import FileTypeSettings from './components/FileTypeSettings.vue'
import { cacheManager, createCacheEntry } from './utils/cache'

interface DirectoryResult {
  success: boolean;
  path?: string;
  error?: string;
}

interface ScanResult {
  completed: boolean;
  result: {
    total_files: number;
    duplicate_groups: number;
    duplicate_files: number;
    saved_space: string;
    groups: Array<{
      files: Array<{
        name: string;
        path: string;
        size: number;
        modified: number;
      }>;
      size: number;
    }>;
    total_size?: string;
  };
}

interface FileInfo {
  name: string;
  path: string;
  size: number;
  modified: Date;
  selected: boolean;
}

interface DuplicateGroup {
  files: FileInfo[];
  size: number;
}

// 页面状态
const currentView = ref<'home' | 'settings' | 'scanning' | 'results' | 'cache' | 'help' | 'fileTypes'>('home')

// 扫描设置
const scanMode = ref('thorough')
const detectionMode = ref('exact')
const similarityThreshold = ref(90)
const scanPath = ref('')
const minFileSize = ref('0')
const maxFileSize = ref('0')

// 扫描进度
const scanProgress = ref(0)
const currentStatus = ref('准备扫描...')
const currentStage = ref('')
const currentSubStatus = ref('')
const scannedFiles = ref(0)
const duplicateGroups = ref(0)
const savedSpace = ref('0 B')

// 扫描结果
const totalFiles = ref(0)
const duplicateFiles = ref(0)
const duplicateGroupsList = ref<any[]>([])

// 更新重复组数据
const updateDuplicateGroups = (updatedGroups: any[]) => {
  duplicateGroupsList.value = updatedGroups
  console.log('重复组数据已更新:', updatedGroups.length)
}

// 项目记录
const currentProjectRecord = ref<any>(null)

// 组件引用
const scanConfigRef = ref()

// 关于对话框
const showAboutDialog = ref(false)

// 全局右键菜单管理
const contextMenuWhitelist = ref<Set<string>>(new Set())

// 注册允许右键菜单的元素
const registerContextMenu = (elementId: string) => {
  contextMenuWhitelist.value.add(elementId)
}

// 注销允许右键菜单的元素
const unregisterContextMenu = (elementId: string) => {
  contextMenuWhitelist.value.delete(elementId)
}

// 处理全局右键菜单
const handleGlobalContextMenu = (event: MouseEvent) => {
  const target = event.target as HTMLElement
  
  // 检查目标元素是否在右键菜单白名单中
  let hasContextMenu = false
  let currentElement: HTMLElement | null = target
  
  while (currentElement && currentElement !== document.body) {
    // 检查元素是否有data-context-menu-id属性
    const contextMenuId = currentElement.getAttribute('data-context-menu-id')
    if (contextMenuId && contextMenuWhitelist.value.has(contextMenuId)) {
      hasContextMenu = true
      break
    }
    
    // 检查元素是否有data-allow-context-menu属性
    if (currentElement.hasAttribute('data-allow-context-menu')) {
      hasContextMenu = true
      break
    }
    
    currentElement = currentElement.parentElement
  }
  
  // 如果不在白名单中，阻止右键菜单
  if (!hasContextMenu) {
    event.preventDefault()
    event.stopPropagation()
    console.log('右键菜单已被屏蔽')
  }
}

// 全局禁止选择文本
const handleGlobalSelection = (event: Event) => {
  const target = event.target as HTMLElement
  
  // 检查目标元素是否允许选择文本
  let allowSelection = false
  let currentElement: HTMLElement | null = target
  
  while (currentElement && currentElement !== document.body) {
    // 检查元素是否有data-allow-selection属性
    if (currentElement.hasAttribute('data-allow-selection')) {
      allowSelection = true
      break
    }
    
    // 检查元素是否有data-context-menu-id属性（右键菜单元素也允许选择）
    const contextMenuId = currentElement.getAttribute('data-context-menu-id')
    if (contextMenuId && contextMenuWhitelist.value.has(contextMenuId)) {
      allowSelection = true
      break
    }
    
    currentElement = currentElement.parentElement
  }
  
  // 如果不允许选择，阻止选择事件
  if (!allowSelection) {
    event.preventDefault()
    event.stopPropagation()
    
    // 清除已选择的文本
    if (window.getSelection) {
      const selection = window.getSelection()
      if (selection && selection.toString().length > 0) {
        selection.removeAllRanges()
      }
    }
  }
}

// 弹窗定位管理
const modalRef = ref<HTMLElement | null>(null)

// 动态定位弹窗
const positionModal = () => {
  if (modalRef.value) {
    const modal = modalRef.value
    // 使用absolute定位避免fixed问题
    modal.style.position = 'absolute'
    modal.style.top = '0px'
    modal.style.left = '0px'
    modal.style.width = '100%'
    modal.style.height = '100%'
    modal.style.zIndex = '9999'
    
    // 确保弹窗内容居中
    const content = modal.querySelector('.modal-content') as HTMLElement
    if (content) {
      content.style.position = 'absolute'
      content.style.top = '50%'
      content.style.left = '50%'
      content.style.transform = 'translate(-50%, -50%)'
    }
  }
}

// 监听窗口变化
const handleResize = () => {
  positionModal()
}

// 显示关于对话框时重新定位
const showAbout = () => {
  showAboutDialog.value = true
  // 使用nextTick确保DOM更新后再定位
  nextTick(() => {
    positionModal()
  })
}

// 退出应用
const exitApp = async () => {
  try {
    // 使用Tauri的退出API
    const { exit } = await import('@tauri-apps/api/process')
    await exit(0)
  } catch (error) {
    console.error('退出应用失败:', error)
    // 备用方案
    window.close()
  }
}

// 清除缓存
const clearCache = () => {
  cacheManager.clear()
  console.log('缓存已清除')
}

// 选择目录
const selectDirectory = async () => {
  console.log('开始选择目录...')
  try {
    const result: DirectoryResult = await invoke('select_directory')
    console.log('API调用结果:', result)
    
    if (result.success && result.path) {
      scanPath.value = result.path
      console.log('选择的路径:', result.path)
      
      // 检查是否有项目记录
      checkProjectRecord(result.path)
    } else {
      console.log('选择目录失败:', result.error)
    }
  } catch (error) {
    console.error('选择目录失败:', error)
  }
}

// 检查项目记录
const checkProjectRecord = (path: string) => {
  // 获取检测模式设置
  const detectionMode = scanConfigRef.value?.detectionMode || 'exact'
  const similarityThreshold = scanConfigRef.value?.similarityThreshold || 90
  
  const cachedResult = cacheManager.get(
    path,
    scanMode.value,
    detectionMode,
    similarityThreshold,
    parseInt(minFileSize.value),
    parseInt(maxFileSize.value)
  )
  
  if (cachedResult) {
    console.log('发现项目记录:', cachedResult)
    currentProjectRecord.value = {
      totalFiles: cachedResult.totalFiles,
      duplicateGroups: cachedResult.duplicateGroups
    }
  } else {
    currentProjectRecord.value = null
  }
}

// 开始扫描
const startScan = async (params: { extensions?: string[] } = {}) => {
  if (!scanPath.value) {
    console.log('请选择扫描路径')
    return
  }

  // 获取检测模式设置
  const detectionMode = scanConfigRef.value?.detectionMode || 'exact'
  const similarityThreshold = scanConfigRef.value?.similarityThreshold || 90

  console.log('开始扫描，检测模式:', detectionMode, '相似性阈值:', similarityThreshold)
  console.log('扫描路径:', scanPath.value)
  console.log('扫描模式:', scanMode.value)
  console.log('文件大小限制: 最小 {} B, 最大 {} B', 
    minFileSize.value === '0' ? '无限制' : minFileSize.value,
    maxFileSize.value === '0' ? '无限制' : maxFileSize.value
  )

  try {
    console.log('开始扫描，路径:', scanPath.value)
    
    // 清理之前的状态，防止与之前的扫描操作冲突
    scanProgress.value = 0
    currentStatus.value = '正在准备扫描...'
    currentStage.value = ''
    currentSubStatus.value = ''
    scannedFiles.value = 0
    duplicateGroups.value = 0
    duplicateFiles.value = 0
    savedSpace.value = '0 B'
    duplicateGroupsList.value = []
    
    // 切换到扫描页面
    currentView.value = 'scanning'
    
    // 等待DOM更新完成
    await nextTick()
    
    // 调用后端扫描API
    const result: ScanResult = await invoke('scan_directory_with_progress', {
      request: {
        path: scanPath.value,
        scan_mode: scanMode.value,
        detection_mode: detectionMode,
        similarity_threshold: similarityThreshold,
        min_file_size: parseInt(minFileSize.value),
        max_file_size: parseInt(maxFileSize.value),
        file_extensions: params.extensions || []
      }
    })
    
    console.log('invoke调用完成，结果类型:', typeof result)
    console.log('Rust实时进度扫描结果:', result)
    
    // 验证结果数据
    if (!result || typeof result !== 'object') {
      throw new Error('扫描结果格式错误')
    }
    
    // 检查是否是实时进度结果
    if (result.completed && result.result) {
      const scanResult = result.result
      
      // 更新进度到100%，显示扫描完成
      scanProgress.value = 100
      currentStatus.value = '扫描完成！'
      
      // 立即更新文件数量，让用户看到扫描结果
      scannedFiles.value = scanResult.total_files || 0
      totalFiles.value = scanResult.total_files || 0
      
      // 更新结果数据
      duplicateGroups.value = scanResult.duplicate_groups || 0
      duplicateFiles.value = scanResult.duplicate_files || 0
      savedSpace.value = scanResult.saved_space || '0 B'
      
      // 显示最终统计信息
      currentStatus.value = `扫描完成！发现 ${scanResult.total_files || 0} 个文件，${scanResult.duplicate_groups || 0} 个重复组，可节省空间 ${scanResult.saved_space || '0 B'}`
      
      console.log('更新后的数据:', {
        totalFiles: totalFiles.value,
        duplicateGroups: duplicateGroups.value,
        duplicateFiles: duplicateFiles.value,
        savedSpace: savedSpace.value,
        scannedFiles: scannedFiles.value
      })
      
      // 转换结果数据格式
      if (scanResult.groups && Array.isArray(scanResult.groups)) {
        duplicateGroupsList.value = scanResult.groups.map((group: { files: Array<{ name: string; path: string; size: number; modified: number; }>; size: number; }) => ({
          files: group.files.map((file: { name: string; path: string; size: number; modified: number; }) => ({
            name: file.name,
            path: file.path,
            size: file.size,
            modified: new Date(file.modified * 1000),
            selected: false
          })),
          size: group.size
        }))
        console.log('转换后的重复组:', duplicateGroupsList.value.length)
      } else {
        console.warn('结果中没有groups数据或格式错误')
        duplicateGroupsList.value = []
      }

      // 保存到项目记录
      try {
        const cacheEntry = createCacheEntry({
          path: scanPath.value,
          scanMode: scanMode.value,
          detectionMode,
          similarityThreshold,
          minFileSize: parseInt(minFileSize.value),
          maxFileSize: parseInt(maxFileSize.value),
          totalFiles: scanResult.total_files || 0,
          duplicateGroups: scanResult.duplicate_groups || 0,
          duplicateFiles: scanResult.duplicate_files || 0,
          savedSpace: scanResult.saved_space || '0 B',
          groups: scanResult.groups || [],
          fileCount: scanResult.total_files || 0,
          totalSize: scanResult.total_size || '0 B'
        })
        
        cacheManager.set(cacheEntry)
        console.log('扫描结果已保存到项目记录')
        
        // 更新当前项目记录信息
        currentProjectRecord.value = {
          totalFiles: scanResult.total_files || 0,
          duplicateGroups: scanResult.duplicate_groups || 0
        }
      } catch (error) {
        console.warn('保存项目记录失败:', error)
      }
      
      // 延迟跳转，让用户看到完成状态
      // 使用 nextTick 确保DOM更新完成后再跳转
      nextTick(() => {
        setTimeout(() => {
          // 检查是否还在扫描状态，避免与新的扫描操作冲突
          if (currentView.value === 'scanning') {
            currentView.value = 'results'
          }
        }, 2000)
      })
      
    } else {
      throw new Error('实时进度扫描未完成或结果格式错误')
    }
    
  } catch (error) {
    console.error('扫描失败:', error)
    
    // 检查是否是用户主动取消
    if (error === '用户取消了扫描') {
      console.log('用户主动取消扫描，不显示错误提示')
      currentView.value = 'settings'
      scanProgress.value = 0
      currentStatus.value = '扫描已取消'
    } else {
      // 真正的扫描错误才显示提示
      alert('扫描失败: ' + error)
      currentView.value = 'settings'
    }
  }
}

// 取消扫描
const cancelScan = async () => {
  try {
    console.log('用户取消扫描')
    
    // 调用后端取消扫描命令
    await invoke('cancel_scan')
    console.log('后端取消扫描命令已发送')
    
    // 重置扫描状态
    currentView.value = 'settings'
    scanProgress.value = 0
    currentStatus.value = '扫描已取消'
    currentStage.value = ''
    currentSubStatus.value = ''
    scannedFiles.value = 0
    duplicateGroups.value = 0
    savedSpace.value = '0 B'
    
    // 清理事件监听器
    cleanupEventListeners()
    
    // 重新设置事件监听器
    setupEventListeners()
  } catch (error) {
    console.error('取消扫描失败:', error)
    // 即使后端调用失败，也要重置前端状态
    currentView.value = 'settings'
    scanProgress.value = 0
    currentStatus.value = '扫描已取消'
  }
}

// 生成模拟结果数据
const generateMockResults = () => {
  totalFiles.value = scannedFiles.value
  duplicateFiles.value = 75
  
  duplicateGroupsList.value = [
    {
      files: [
        { name: 'photo1.jpg', path: 'C:/Photos/photo1.jpg', size: 2048576, modified: new Date(), selected: false },
        { name: 'photo1_copy.jpg', path: 'C:/Photos/Backup/photo1_copy.jpg', size: 2048576, modified: new Date(), selected: false },
        { name: 'photo1_副本.jpg', path: 'C:/Photos/副本/photo1_副本.jpg', size: 2048576, modified: new Date(), selected: false }
      ],
      size: 2048576
    },
    {
      files: [
        { name: 'document.pdf', path: 'C:/Documents/document.pdf', size: 1048576, modified: new Date(), selected: false },
        { name: 'document.pdf', path: 'C:/Documents/Archive/document.pdf', size: 1048576, modified: new Date(), selected: false }
      ],
      size: 1048576
    }
  ]
}

// 测试Tauri API
const testTauriAPI = async () => {
  console.log('测试Tauri API...')
  
  try {
    const result = await invoke('test_command')
    console.log('Tauri API 测试成功！结果:', result)
  } catch (error) {
    console.error('Tauri API 测试失败:', error)
  }
}

// 获取当前扫描阶段
const getCurrentStage = (): string => {
  if (scanProgress.value < 20) return 'scanning'
  if (scanProgress.value < 60) return 'analyzing'
  if (scanProgress.value < 80) return 'comparing'
  if (scanProgress.value < 95) return 'reporting'
  return 'completed'
}

// 获取子状态信息
const getSubStatus = (): string => {
  if (scanProgress.value < 20) return '正在统计目录中的文件数量...'
  if (scanProgress.value < 60) return '正在扫描文件并计算哈希值...'
  if (scanProgress.value < 80) return '正在分析文件内容...'
  if (scanProgress.value < 95) return '正在比较重复文件...'
  return '扫描完成，正在生成报告...'
}

// 从项目记录加载结果
const loadFromCache = (entry: any) => {
  console.log('从项目记录加载:', entry)
  
  // 设置扫描路径
  scanPath.value = entry.path
  
  // 更新数据
  totalFiles.value = entry.totalFiles
  duplicateGroups.value = entry.duplicateGroups
  duplicateFiles.value = entry.duplicateFiles
  savedSpace.value = entry.savedSpace
  scannedFiles.value = entry.totalFiles
  
  // 转换项目记录的数据格式
  if (entry.groups && Array.isArray(entry.groups)) {
    duplicateGroupsList.value = entry.groups.map((group: any) => ({
      files: group.files.map((file: any) => ({
        name: file.name,
        path: file.path,
        size: file.size,
        modified: new Date(file.modified * 1000),
        selected: false
      })),
      size: group.size
    }))
  }
  
  // 跳转到结果页面
  currentView.value = 'results'
}

// 从缓存加载并跳转到扫描页面
const goToScanFromCache = () => {
  console.log('从缓存加载并跳转到扫描页面')
  // 假设缓存加载成功后，scanPath.value 和 scanMode.value 等已经更新
  // 这里可以重新检查项目记录，确保数据是最新的
  checkProjectRecord(scanPath.value)
  currentView.value = 'scanning'
  scanProgress.value = 0
  currentStatus.value = '正在准备扫描...'
  scannedFiles.value = 0
  duplicateGroups.value = 0
  savedSpace.value = '0 B'
}

// 事件监听器
let unlistenScanProgress: (() => void) | null = null

// 设置事件监听器
const setupEventListeners = async () => {
  try {
    unlistenScanProgress = await listen('scan_progress', (event) => {
      console.log('收到进度更新事件:', event.payload)
      const progress = event.payload as any
      
      // 实时更新进度
      scanProgress.value = Number(progress.percentage) || 0
      currentStatus.value = progress.message
      currentStage.value = progress.stage || ''
      currentSubStatus.value = progress.sub_status || ''
      
      // 根据阶段更新数据
      switch (progress.stage) {
        case 'scanning_files':
          // 开始扫描文件
          currentStatus.value = progress.message
          break
        case 'files_scanned':
          // 文件扫描完成
          scannedFiles.value = progress.current
          totalFiles.value = progress.total
          currentStatus.value = progress.message
          console.log('文件扫描完成，更新统计信息:', { scanned: scannedFiles.value, total: totalFiles.value })
          break
        case 'calculating_hashes':
          // 正在计算文件哈希值
          currentStatus.value = progress.message
          console.log('正在计算文件哈希值，进度:', progress.percentage)
          break
        case 'hashes_calculated':
          // 文件哈希值计算完成
          currentStatus.value = progress.message
          console.log('文件哈希值计算完成')
          break
        case 'analyzing_duplicates':
          // 开始分析重复文件
          currentStatus.value = progress.message
          console.log('开始分析重复文件阶段')
          break
        case 'duplicates_analyzed':
          // 重复文件分析完成
          currentStatus.value = progress.message
          console.log('重复文件分析完成')
          // 这里可以更新重复组数量等
          break
        case 'completed':
          // 最终完成
          currentStatus.value = progress.message
          console.log('扫描完全完成')
          break
        default:
          // 处理其他阶段或未知阶段
          console.log('未知进度阶段:', progress.stage)
          break
      }
      
      // 强制触发Vue响应式更新
      console.log('当前状态更新:', {
        stage: currentStage.value,
        status: currentStatus.value,
        progress: scanProgress.value,
        scannedFiles: scannedFiles.value
      })
    })
    console.log('进度事件监听器设置成功')
  } catch (error) {
    console.error('设置事件监听器失败:', error)
  }
}

// 清理事件监听器
const cleanupEventListeners = () => {
  if (unlistenScanProgress) {
    unlistenScanProgress()
    unlistenScanProgress = null
    console.log('进度事件监听器已清理')
  }
}

// 向子组件提供全局右键菜单管理函数
provide('registerContextMenu', registerContextMenu)
provide('unregisterContextMenu', unregisterContextMenu)

// 组件挂载时设置监听器
onMounted(() => {
  setupEventListeners()
  // 监听窗口变化，确保弹窗正确定位
  window.addEventListener('resize', handleResize)
  // 初始定位弹窗
  positionModal()
  
  // 添加全局事件监听器
  document.addEventListener('contextmenu', handleGlobalContextMenu, true)
  document.addEventListener('selectstart', handleGlobalSelection, true)
  document.addEventListener('mousedown', handleGlobalSelection, true)
})

// 组件卸载时清理监听器
onUnmounted(() => {
  cleanupEventListeners()
  // 移除窗口变化监听器
  window.removeEventListener('resize', handleResize)
  
  // 移除全局事件监听器
  document.removeEventListener('contextmenu', handleGlobalContextMenu, true)
  document.removeEventListener('selectstart', handleGlobalSelection, true)
  document.removeEventListener('mousedown', handleGlobalSelection, true)
})
</script>
